#!/usr/bin/env python
# -*- coding:utf-8 -*-

import _tkinter
import tkinter as tk
from tkinter import ttk
from common.transmission.secure_channel import establish_secure_channel_to_server
from tkinter import messagebox
from common.message import MessageType
from pprint import pprint
from client.memory import current_user
from common.transmission.secure_channel import get_ip
import select
import client.util.socket_listener
from common.config import get_config
import client.memory
import socket
from tkinter import *
from tkinter import Toplevel
import re
import random

""" 注册操作 """
class RegisterForm(tk.Frame):
    """ 打开事件监听 """
    def socket_listener(self, data):
        if data['type'] == MessageType.username_taken:
            messagebox.showerror('Error', '用户名已被使用，请换一个')
            return

        if data['type'] == MessageType.register_successful:
            messagebox.showinfo('Congratulations', '恭喜，注册成功，您成为第' + str(data['parameters'])+'个用户')
            self.remove_socket_listener_and_close()
            return

    """ 关闭监听 """
    def remove_socket_listener_and_close(self):
        client.util.socket_listener.remove_listener(self.socket_listener)
        self.master.destroy()

    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.sc = client.memory.sc

        self.master.title("Uchat——注册")
        master.resizable(width=False, height=False)
        master.geometry('480x400')  # Adjusted height

        # Generate a 6-digit random number
        random_number = ''.join(random.choices('0123456789', k=6))

        # Canvas
        self.canvas = tk.Canvas(self.master, width=480, height=400)  # Adjusted height
        self.image_file = tk.PhotoImage(file='client/forms/images/register_bg.gif')
        self.image = self.canvas.create_image(0, 0, anchor='nw', image=self.image_file)

        # Labels
        self.user_name = tk.Label(self.master, text="用户名", font=("楷体", 16), fg="black", bg="#30cfe8")
        self.user_pwd = tk.Label(self.master, text="密  码", font=("楷体", 16), fg="black", bg="#32d0ea")
        self.confirm_pwd = tk.Label(self.master, text="确认密码", font=("楷体", 16), fg="black", bg="#3ad2e9")

        # Input fields
        # Username
        self.var_user_name = tk.StringVar()
        self.var_user_name.set(random_number)  # Default random username
        self.entry_user_name = tk.Entry(self.master, textvariable=self.var_user_name, font=("楷体", 18), fg="black",
                                        bg="#4ed8eb", relief=GROOVE)
        # Password
        self.var_user_pwd = tk.StringVar()
        self.var_user_pwd.set(random_number)  # Default random password
        self.entry_user_pwd = tk.Entry(self.master, textvariable=self.var_user_pwd, show='* ', font=("楷体", 18),
                                       fg="black", bg="#48d7ec", relief=GROOVE)
        # Confirm password
        self.var_confirm_pwd = tk.StringVar()
        self.var_confirm_pwd.set(random_number) # Default random password
        self.entry_confirm_pwd = tk.Entry(self.master, textvariable=self.var_confirm_pwd, show='* ', font=("楷体", 18),
                                          fg="black", bg="#54d9ec", relief=GROOVE)

        # Register button
        self.register_btn = tk.Button(self.master, text='       注     册       ', font=("楷体", 18), fg="black",
                                      bg="#5edbee", activebackground="#61d8ee", relief=GROOVE, width=30,
                                      command=self.do_register)

        # Grid layout
        self.canvas.grid(row=0, column=0, rowspan=12, columnspan=8)  # Adjusted rowspan

        self.user_name.grid(row=6, column=1, columnspan=2, sticky=E)  # Adjusted row
        self.user_pwd.grid(row=7, column=1, columnspan=2, sticky=E)  # Adjusted row
        self.confirm_pwd.grid(row=8, column=1, columnspan=2, sticky=E)  # Adjusted row

        self.entry_user_name.grid(row=6, column=3, columnspan=3, sticky=W)  # Adjusted row
        self.entry_user_pwd.grid(row=7, column=3, columnspan=3, sticky=W)  # Adjusted row
        self.entry_confirm_pwd.grid(row=8, column=3, columnspan=3, sticky=W)  # Adjusted row

        self.register_btn.grid(row=9, column=2, columnspan=4, sticky=S+W)  # Adjusted row

        self.sc = client.memory.sc
        client.util.socket_listener.add_listener(self.socket_listener)
        master.protocol("WM_DELETE_WINDOW", self.remove_socket_listener_and_close)

    """" 注册操作 """
    def do_register(self):

        username = self.var_user_name.get()
        password = self.var_user_pwd.get()
        password_confirmation = self.var_confirm_pwd.get()

        ip = get_ip()
        config = get_config()
        port = str((config['client']['client_port']))

        if not username:
            messagebox.showerror("Error", "用户名不能为空")
            return
        if not password:
            messagebox.showerror("Error", "密码不能为空")
            return
        if password != password_confirmation:
            messagebox.showerror("Error", "两次密码输入不一致")
            return

        self.sc.send(MessageType.register, [username, password, "", ip, port, "", ""])  # send empty values

        certname = ip + "_cert.pem"
        with open(certname, 'rb') as f:
            context = f.read()
            sp = context.split()
            f.close()

        with open(certname,'wb') as f:
            f.write((str(self.var_user_name.get()) + ' ' + " "+ str(sp[2])).encode())
            f.close()